<?php

namespace Admin\Controller;

use Think\Image;
use Think\Upload;

class GoodController extends PublicController
{
    function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 活动首页
     */
    public function index()
    {
        $m = M("Good");
        $keyword = I('post.keyword');
        $menu_id = I('post.menu_id');
        if ($menu_id) {
            if ($menu_id != -1) {
                $where['menu_id'] = $menu_id;
            }
        }
        if ($keyword) {
            $where['g.name'] = array('like', "%$keyword%");
        }

        if (empty($menu_id) && empty($keyword)) {
            $where = "1=1";
        }
        $count = count($m->alias("g")->where($where)->order("time")->select());

        $Page = new \Think\Page($count, 12);
        $Page->setConfig('theme', "<ul class='pagination no-margin pull-right'></li><li>%FIRST%</li><li>%UP_PAGE%</li><li>%LINK_PAGE%</li><li>%DOWN_PAGE%</li><li>%END%</li><li><a> %HEADER%  %NOW_PAGE%/%TOTAL_PAGE% 页</a></ul>");
        $show = $Page->show(); // 分页显示输出
        $result = $m->alias("g")->join("left join xier_menu as m on m.id=g.menu_id")->field('g.id,g.name,g.menu_id,g.zjname,g.num,g.snum,g.dz,g.jl,m.name as menu_name,g.time,g.people,g.is_online,g.group_id,g.recommend')->limit($Page->firstRow . ',' . $Page->listRows)->where($where)->order("id desc")->select();
        foreach ($result as $key => $val) {
            if ($val['is_online'] == 1) {
                $result[$key]['online'] = '上线';
            } else {
                $result[$key]['online'] = '下线';
            }

            $group_id = $val['group_id'];
            if (!empty($group_id)) {
                $ids = explode(',', $group_id);
                $result[$key]['group_name'] = '';
                for ($i = 0; $i < count($ids); $i++) {
                    $id = $ids[$i];
                    $result[$key]['group_name'] .= M('group')->where("id=$id")->getField('name') . ',';
                }
            }

        }
        $this->assign("menu_id", $menu_id);
        $this->assign("keyword", $keyword);
        $this->assign("page", $show); // 赋值分页输出
        $menu = M("Menu")->select();
        $this->assign('menu', $menu);
        $this->assign('result', $result);
        $this->display();
    }

    /**
     * 活动增加修改
     */
    public function edit()
    {
        $id = I('get.id');
        if ($id) {
            $result = M("Good")->where("id='$id'")->find();
            if ($result['is_online'] == 1) {
                $result['online'] = '上线';
            } else {
                $result['online'] = '下线';
            }
            $start_time = date('Y-m-d', $result['start_time']);
            $end_time = date('Y-m-d', $result['start_time']);

            $this->assign('start_time', $start_time);
            $this->assign('end_time', $end_time);
            $this->assign('result', $result);
            $this->assign("menu_id", $result['menu_id']);
            //查出轮播图
            $banner = M("Good_pic")->where("good_id='$id'")->select();
            $this->assign('banner', $banner);
        }
        $group = M('group')->select();
        $menu = M("Menu")->select();
        $this->assign('group', $group);
        $this->assign('id', $id);
        $this->assign('now', date('Y-m-d'), time());
        $this->assign('menu', $menu);
        $this->display();
    }

    /**
     * 增加活动
     */
    public function editGood()
    {
        $data = I();
        $id = I('post.id');
        if ($data['group_id']) {
            $data['group_id'] = implode(',', $data['group_id']);
        }
        $data['time'] = time();

        if ($data['long'] == 1) {
            $data['start_time'] = '';
            $data['end_time'] = '';
        } else {
            $data['start_time'] = strtotime($data['start_time']);
            $data['end_time'] = strtotime($data['end_time']);
        }
        $Model = M();
        $Model->startTrans();
        if ($id) {
            //编辑
            $result = M('good')->where("id='$id'")->save($data);
            if ($result !== false) {
                $Model->commit();
                $this->success("操作成功", U('Good/index'));
            } else {
                $Model->rollback();
                $this->error("操作失败");
            }
        } else {
            //新增
            $result = M('good')->add($data);
            if ($result !== false) {
                $Model->commit();
                $this->success("操作成功", 'Good/index');
            } else {
                $Model->rollback();
                $this->error("操作失败");
            }
        }
    }

    /**
     * 删除活动信息
     */
    public function delGood()
    {
        $id = I("get.id");
        $Model = M();
        $Model->startTrans();
        //删除轮播的image
//        $images = M("GoodPic")->field('pic')->where("good_id = $id")->select();//图标找出来
        //删除good表的数据
        $result = M("Good")->where(array(
            'id' => $id
        ))->delete();
        //删除good_pic表的数据
//        $img_delete = M("GoodPic")->where(array(
//            'good_id' => $id
//        ))->delete();
        if ($result !== false) {
            $Model->commit();
            $this->success("删除成功");
        } else {
            $Model->rollback();
            $this->error("操作失败");
        }
    }

    public function activityGoodadd(){
        $id = I('request.id');
        $title = I('request.title');
        $yuanjia = I('request.yuanjia');
        $xianjia = I('request.xianjia');
        $con = I('request.con');
        $file = $_FILES['img1'];
        $info = '';
        if ($file) {

            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     113145728 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg',"RM","RMVB","AVI","WMV","MPG ","MPEG","FLV","3GP","MP4","SWF","ASF","DIVX","XVID","3GP2","FLV1","MPEG1","MPEG2","MPEG3","MPEG4","H264",'rm','rmvb','avi','wmv','mpg','mpeg','flv','3gp','mp4','swf','asf','divx','xvid','3gp2','flv1','mpeg1','mpeg2','mpeg3','mpeg4','h264');// 设置附件上传类型
            $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
            $upload->savePath  =     'mov/'; // 设置附件上传（子）目录
            // 上传文件 
            $info   = $upload->upload();

        }
            $data['title'] = $title;
            $data['con'] = $con;
            $data['yuanjia'] = $yuanjia;
            $data['xianjia'] = $xianjia;
            if ($info) {
                foreach ($info as $k => $v) {
                    $data['img'] = 'Uploads/'.$v['savepath'].$v['savename'];
                }
            }
            if ($id) {
                $where['id'] = $id;
                $res = M('hg')->where($where)->save($data);
            }else{
                $res = M('hg')->add($data);
            }

            if ($res) {
                $this->success("成功",U('Good/activityGood'));
            } else {
                $this->error("操作失败");
            }
    }

    /**
     * 活动记录
     */
    public function activityList()
    {
        $where['c.status'] = array('eq',0);
        $count = M('ceping')
        ->alias('c')
        ->join('left join xier_user as u on u.id=c.uid')
        ->where($where)
        ->count();
        $Page = new \Think\Page($count, 12);
        $Page->setConfig('theme', "<ul class='pagination no-margin pull-right'></li><li>%FIRST%</li><li>%UP_PAGE%</li><li>%LINK_PAGE%</li><li>%DOWN_PAGE%</li><li>%END%</li><li><a> %HEADER%  %NOW_PAGE%/%TOTAL_PAGE% 页</a></ul>");
     
        $show = $Page->show(); // 分页显示输出
        //获取活动列表
        $list = M('ceping')
                ->alias('c')
                ->field('c.*,u.nickname')
                ->join('left join xier_user as u on u.id=c.uid')
                ->limit($Page->firstRow . ',' . $Page->listRows)
                ->where($where)
                ->select();
        $this->assign('list', $list);
        $this->assign("page", $show); // 赋值分页输出
        $this->display();
    }

        /**
     * 活动记录
     */
    public function activityGood()
    {

        $count = M('hg')
        ->count();
        $Page = new \Think\Page($count, 12);
        $Page->setConfig('theme', "<ul class='pagination no-margin pull-right'></li><li>%FIRST%</li><li>%UP_PAGE%</li><li>%LINK_PAGE%</li><li>%DOWN_PAGE%</li><li>%END%</li><li><a> %HEADER%  %NOW_PAGE%/%TOTAL_PAGE% 页</a></ul>");
     
        $show = $Page->show(); // 分页显示输出
        //获取活动列表
        $list = M('hg')
   
                ->limit($Page->firstRow . ',' . $Page->listRows)

                ->select();
        $this->assign('list', $list);
        $this->assign("page", $show); // 赋值分页输出
        $this->display();
    }

    public function edit_a_good(){
        $id = I('request.id');
        if ($id) {
            $where['id'] = array('eq',$id);
            $data = M('hg')->where($where)->find();
            $this->assign('result',$data);
            $this->assign('PATH',PATH);
        }
        $this->display();
    }

    /**
     * 导出
     */
    public function export()
    {
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Writer.Excel5");
        import("Org.Util.PHPExcel.IOFactory.php");
        $keyword = I('request.keyword');
        $menu_id = I('request.menu_id');
        $end_time = strtotime(I('request.end_time'));
        $start_time = strtotime(I('request.start_time'));
        if ($menu_id) {
            if ($menu_id != -1) {
                $where['menu_id'] = $menu_id;
            }
        }
        if ($keyword) {
            $where['name'] = array('like', "%$keyword%");
        }
        if ($start_time && $end_time) {
            $where['time'] = array('between', "$start_time,$end_time");
        } elseif ($start_time && empty($end_time)) {
            $where['time'] = array('egt', $start_time);
        } elseif ($end_time && empty($start_time)) {
            $where['time'] = array('elt', $end_time);
        }
        if (empty($menu_id) && empty($keyword)) {
            $where = "1=1";
        }
//        $result = M('good')->where($where)->field(array('id', 'name', 'start_time', 'end_time'))->select();
        $result = M('activity')->alias("a")->where($where)->join("left join xier_good as g on a.goods_id=g.id")->join("inner join xier_menu as m on m.id=g.menu_id")->field(array("a.id,g.name,g.start_time,g.end_time,count(*) as num,m.name as menu_name"))->group("a.goods_id")->select();
//        echo  M()->_sql();exit;
        foreach ($result as $key => $v) {
//            $goods_id = $v['id'];
//            $goods_result = M('good')->where("id='$goods_id'")->find();
//            $menu_ids = $goods_result['menu_id'];
//            $result[$key]['menu_name'] = M('menu')->where("id='$menu_ids'")->getField('name');
//            $result[$key]['num'] = M('activity')->where("goods_id='$goods_id'")->count();
            if (empty($v['start_time'])) {
                $result[$key]['start_time'] = '         ';
            } else {
                $result[$key]['start_time'] = date('Y-m-d', $v['start_time']);
            }
            if (empty($v['end_time'])) {
                $result[$key]['end_time'] = '         ';
            } else {
                $result[$key]['end_time'] = date('Y-m-d', $v['end_time']);
            }
        }
//        dump($result);exit;
        $filename = "活动";
        $headArr = array("ID", "活动名称", "活动开始时间", "活动结束时间", "活动人数", "活动分类");
        $this->getExcel($filename, $headArr, $result);
    }

    /**
     * 删除活动记录
     */
    public function delActivity()
    {
        $id = I('request.id');       
         $where['id'] = array('eq',$id);
        $result = M('ceping')->where($where)->delete();
        $this->success("操作成功");
    }

    /**
     * 搜索群组
     */
    public function searchGroup()
    {
        $search = I('request.search');
        $where['name'] = array('like', "$search%");
        $result = M("group")->where($where)->select();
//        $this->ajaxReturn(M()->_sql());
        if ($result) {
            $this->ajaxReturn(array('state' => 1, 'data' => $result), 'json');
        } else {
            $this->ajaxReturn(array('state' => 0), 'json');
        }
    }


    //详情 
    public function edit_a(){
        $id = I('request.id');
        $where['c.id'] = array('eq',$id);
        $list = M('ceping')
                ->alias('c')
                ->field('c.*,u.nickname')
                ->join('left join xier_user as u on u.id=c.uid')
                ->where($where)
                ->find();               
        $this->assign("result", $list); // 赋值分页输出
        $this->display();        
    }
    /**
     * 设置推荐
     */
    public function recommend(){
        $id=I('request.id');
        $recommend=M('good')->where("id='$id'")->getField('recommend');
        //推荐改为不推荐
        if($recommend==1){
            $result=M('good')->where("id='$id'")->setField('recommend',2);
        }else{
            //不推荐改为推荐
            $result=M('good')->where("id='$id'")->setField('recommend',1);
        }
        if($result===false){
            $this->error("设置失败");
        }else{
            $this->success("设置成功",'Admin/Good/index');
        }
    }

}